package com.yycwxt.modules.admin.data_import;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.yycwxt.common.BaseService;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Service
@Transactional
public class ImpFileService extends BaseService<ImpFileMapper, ImpFile> {
    private final ImpFileMapper impFileMapper;

    public ImpFileService(ImpFileMapper impFileMapper) {
        this.impFileMapper = impFileMapper;
    }

    public List<ImpFile> selectImpFiles(int zq) {
        return impFileMapper.selectImpFiles(zq);
    }

    @SneakyThrows
    @Transactional
    public void importErpStoreOrder(MultipartFile file, List<ERPStoreOrder> list) {
        EasyExcel.read(file.getInputStream(), ERPStoreOrder.class, new ReadListener<ERPStoreOrder>() {

            private static final int BATCH_SIZE = 1000;

            @Override
            public void invoke(ERPStoreOrder data, AnalysisContext context) {
                try {
                    // 提取收货地址省份
                    data.setDhdd(data.getSsx().substring(0, data.getSsx().indexOf(" ")));
                    // 提取快递公司
                    data.setWlgs(data.getWlgs().substring(data.getWlgs().length() - 2));

                    System.out.println(data);
                    // 执行存储过程
                    impFileMapper.importErpStoreOrder(
                            AccountData.getAccountDate(),
                            data.getDdbh(), data.getDpmc(), data.getCkmc(), data.getYsdh(),
                            data.getSsx(), data.getDhdd(), data.getWlgs(), data.getWldh(),
                            data.getHpzls(), data.getHpzs(),
                            data.getYgzl(), data.getQz(), data.getHpsjbm()
                    );
                }
                catch (Exception e){
                    e.printStackTrace();
                    list.add(data);
                }

            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {

            }
        }).sheet().doRead();
    }
}
